﻿using CardMonitor.Model;
using CardMonitor.ViewModel;
using CardMonitor.Windows;
using DotNetSpeech;
using Microsoft.Office.Interop.Excel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CardMonitor.Pages
{
    /// <summary>
    /// ReplaceCard.xaml 的交互逻辑
    /// </summary>
    public partial class ReplaceCard : System.Windows.Controls.Page
    {
        private SpVoice speech = new SpVoice();
        private BillModel billModel = null;
        private SynchronizationContext _syncContext = null;
        private IndexViewModel viewModel;
        private MainWindow mainWindow = null;
        private Action<int, String> callbackAction;
        private KeyBoardWindow inputWindow = null;
        private InputWindow carInputWindow = null;

        public ReplaceCard()
        {
            InitializeComponent();
        }

        public ReplaceCard(MainWindow _win)
        {
            InitializeComponent();
            this.DataContext = billModel;
            billModel = new BillModel();
            this.DataContext = billModel;
            callbackAction += CallBackExcute;
            _syncContext = SynchronizationContext.Current;
            viewModel = new IndexViewModel();
            viewModel.index = 0;
            mainWindow = _win;
            if (billModel.TrailerNumber != null)
            {
                char[] charArray = billModel.TrailerNumber.ToCharArray();

                int len = billModel.TrailerNumber.Length;

                if (len < 8)
                {
                    for (int i = 0; i < billModel.TrailerNumber.Length; i++)
                    {
                        viewModel.carNoArray02.Add(charArray[i].ToString());
                    }

                    for (int i = 0; i < 8 - len; i++)
                    {
                        viewModel.carNoArray02.Add("");
                    }
                }
                else
                {
                    for (int i = 0; i < 8; i++)
                    {
                        viewModel.carNoArray02.Add(charArray[i].ToString());
                    }
                }
            }
            else
            {
                for (int i = 0; i < 8; i++)
                {
                    viewModel.carNoArray02.Add("");
                }
            }
        }

        private void CallBackExcute(int index, string val)
        {
            if (viewModel.index == 3)
            {
                viewModel.carNoArray02[index] = val;
                //BillModel.PiNumberList.Add(val);
                //BillModel.PiNumberList[index] = val;
                billModel.TrailerNumber = String.Join("", viewModel.carNoArray02);
            }

            if (viewModel.index == 1)
            {
                viewModel.waiMaoWeighArray[index] = val;
                //BillModel.PiNumberList.Add(val);
                //BillModel.PiNumberList[index] = val;
                string inputStr = String.Join("", viewModel.waiMaoWeighArray);
                billModel.OuterGrossWeight = inputStr;
            }

            if (viewModel.index == 2)
            {
                viewModel.waiPiWeighArray[index] = val;
                //BillModel.PiNumberList.Add(val);
                //BillModel.PiNumberList[index] = val;
                string inputStr = String.Join("", viewModel.waiPiWeighArray);
                billModel.OuterSkinWeight = inputStr;
            }
        }

        private void goIndex(object sender, RoutedEventArgs e)
        {
            this.NavigationService.GoBack();
        }

        private void showMessage(String message)
        {
            InfoWindow infoWindow = new InfoWindow(message);
            infoWindow.Owner = mainWindow;
            infoWindow.ShowDialog();
        }

        private void SelectCarNum(object sender, RoutedEventArgs e)
        {
            string carNum = SearchBox.Text;
            if (!ValidatePlateNumber(carNum))
            {
                string message = "请输入正确车牌号";
                showMessage(message);
                return;
            }

            HttpPostWindow httpPostWindow = new HttpPostWindow();
            httpPostWindow.Owner = mainWindow;

            JObject paramJSON = new JObject();
            paramJSON.Add("carNumber", carNum);
            httpPostWindow.setParamObject(paramJSON);
            httpPostWindow.setOperation(HttpPostWindow.OperationType.getBillByCarNum.ToString());
            bool result = (bool)httpPostWindow.ShowDialog();
            if (!result)
            {
                string message = httpPostWindow.getMessage();
                if (null == message || "".Equals(message))
                {
                    message = "未查询到单据";
                }
                speech.Speak(message, SpeechVoiceSpeakFlags.SVSFlagsAsync);

                showMessage(message);

                return;
            }
            JArray resultArray = httpPostWindow.getResultArray();
            List<BillModel> billModel = JsonConvert.DeserializeObject<List<BillModel>>(resultArray.ToString());
            SaleCards card = new SaleCards(billModel, mainWindow);
            NavigationService.GetNavigationService(this).Navigate(card);
        }

        private void TextBox_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            string index = (string)((System.Windows.Controls.TextBlock)sender).Tag;
            int v = int.Parse(index);

            _syncContext.Post(showInputWindow, v);
        }

        public String flag = "";

        public void getFlag(String Flag)
        {
            flag = Flag;
        }

        /// <summary>
        /// 车牌号校验（返回"true"或"false"字符串，含新能源）
        /// </summary>
        /// <param name="plateNumber"> 输入的车牌号 </param>
        /// <returns> "true"=合法，"false"=非法 </returns>
        public bool ValidatePlateNumber(string plateNumber)
        {
            // 1. 基础过滤：空值、空白或长度异常（普通7位，新能源8位）
            if (string.IsNullOrWhiteSpace(plateNumber) || (plateNumber.Length != 7 && plateNumber.Length != 8))
                return false;

            // 2. 省份简称校验（前1位必须是合法汉字）
            string[] validProvinces = { "京", "津", "冀", "晋", "蒙", "辽", "吉", "黑", "沪", "苏", "浙", "皖", "闽", "赣", "鲁", "豫", "鄂", "湘", "粤", "桂", "琼", "渝", "川", "贵", "云", "藏", "陕", "甘", "青", "宁", "新" };
            if (!Array.Exists(validProvinces, p => p == plateNumber.Substring(0, 1)))
                return false;

            // 3. 正则校验：排除字母I/O，匹配普通/新能源格式
            bool isNormalPlate = Regex.IsMatch(plateNumber, @"^[\u4e00-\u9fa5][A-HJ-NP-Z][A-HJ-NP-Z0-9]{5}$"); // 普通车牌（7位）
            bool isNewEnergyPlate = Regex.IsMatch(plateNumber, @"^[\u4e00-\u9fa5][A-HJ-NP-Z][A-HJ-NP-Z0-9]{5}[A-HJ-NP-Z]$"); // 新能源（8位）

            return isNormalPlate || isNewEnergyPlate;
        }

        private void showInputWindow(object obj)
        {
            int index = (int)obj;
            viewModel.index = index;
            if (index == 1 || index == 2)
            {
                if (carInputWindow != null)
                {
                    carInputWindow.Hide();
                }

                if (inputWindow == null)
                {
                    inputWindow = new KeyBoardWindow(callbackAction);
                    inputWindow.Owner = mainWindow;
                    inputWindow.Width = mainWindow.Width;
                    inputWindow.Left = mainWindow.Left;
                    inputWindow.Top = SystemParameters.PrimaryScreenHeight - inputWindow.Height;
                }
                inputWindow.maxLength = 7;
                inputWindow.getFlag("2");

                if (index == 2)
                {
                    inputWindow.viewModel.carNoArray.Clear();
                    foreach (String v in viewModel.waiPiWeighArray)
                    {
                        if (v != "")
                        {
                            inputWindow.viewModel.carNoArray.Add(v);
                        }
                    }
                }
                else if (index == 1)
                {
                    inputWindow.viewModel.carNoArray.Clear();
                    foreach (String v in viewModel.waiMaoWeighArray)
                    {
                        if (v != "")
                        {
                            inputWindow.viewModel.carNoArray.Add(v);
                        }
                    }
                }
                inputWindow.showKeys(3);
                inputWindow.Show();
            }
            else if (index == 3)
            {
                if (inputWindow != null)
                {
                    inputWindow.Hide();
                }
                if (carInputWindow == null)
                {
                    carInputWindow = new InputWindow(callbackAction);
                    carInputWindow.Owner = mainWindow;
                    carInputWindow.Width = mainWindow.Width;
                    carInputWindow.Left = mainWindow.Left;
                    carInputWindow.Top = SystemParameters.PrimaryScreenHeight - carInputWindow.Height;
                }
                carInputWindow.maxLength = 8;
                carInputWindow.viewModel.carNoArray.Clear();
                foreach (String v in viewModel.carNoArray02)
                {
                    if (v != "")
                    {
                        carInputWindow.viewModel.carNoArray.Add(v);
                    }
                }
                if (carInputWindow.viewModel.carNoArray.Count == 0)
                {
                    carInputWindow.showKeys(1);
                }
                else
                {
                    carInputWindow.showKeys(2);
                }
                carInputWindow.Show();
            }
            else
            {
                if (inputWindow != null && inputWindow.IsActive)
                {
                    inputWindow.Hide();
                }
                if (carInputWindow != null && carInputWindow.IsActive)
                {
                    carInputWindow.Hide();
                }
            }
        }
    }
}